package com.video.user.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.video.common.enumeration.AppHttpCodeEnum;
import com.video.common.result.PageResult;
import com.video.common.result.ResponseResult;
import com.video.user.config.JwtProperties;
import com.video.user.domain.dto.LoginDto;
import com.video.user.domain.dto.QueryPageDto;
import com.video.user.domain.entity.AdminUser;
import com.video.user.domain.entity.AppUser;
import com.video.user.mapper.AdminUserMapper;
import com.video.user.service.IAdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.video.user.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理用户表 服务实现类
 * </p>
 *
 * @author la
 * @since 2024-11-04
 */
@Service
@RequiredArgsConstructor
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    private final JwtProperties jwtProperties;

    // 导入token生成工具
    private final JwtTool jwtTool;

    /*
     * 登录接口
     * */

    @Override
    public ResponseResult login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        // 查询数据库,判断是否有用户
        AdminUser adminUser = lambdaQuery()
                .eq(username != null, AdminUser::getUsername, username)
                .one();

        // 判断用户是否存在
        if (adminUser == null) {
            return ResponseResult.errorResult(987, "没有找到用户");
        }

        // 判断密码
        if (!DigestUtil.md5Hex(password).equals(adminUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_ERROR);
        }

        // 生成token
        String token = jwtTool.createToken(adminUser.getId(), jwtProperties.getTokenTTL());

        return ResponseResult.okResult(token);
    }


    /*
     * 获取app用户列表
     * */
    @Override
    public PageResult getAppUserList(QueryPageDto dto) {
        // 页码校验
        dto.validateParams();

        // 调用数据库查询参数
        Page<AppUser> page = Db.lambdaQuery(AppUser.class)
                .like(dto.getKeywords() != null, AppUser::getUsername, dto.getKeywords())
                .page(new Page<>(dto.getPage(), dto.getPageSize()));

//        // 批量修改密码
        page.getRecords().forEach(item -> item.setPassword("******"));

        System.out.println("-----------"+page.getRecords());
        return new PageResult(page.getTotal(), page.getRecords());
    }


    /*
     * 新增或编辑用户
     * */
    @Override
    public void updateUser(AppUser user) {
        // 用id 判断是否为新增或编辑
        if (user.getId() == null) {
            user.setPassword(DigestUtil.md5Hex(user.getPassword()));
            user.setCreateTime(System.currentTimeMillis());
            user.setUpdateTime(System.currentTimeMillis());
        } else {
            user.setUpdateTime(System.currentTimeMillis());
            // 判断编辑时密码是否被改变
            if (user.getPassword().equals("******")) {
                user.setPassword(null);
            }
        }

        Db.saveOrUpdate(user);
    }

    /**
     * 获取管理员用户列表
     * @param dto
     * @return
     */

    @Override
    public PageResult getAdminUserList(QueryPageDto dto) {
        // 页码校验
        dto.validateParams();
        Page<AdminUser> page = Db.lambdaQuery(AdminUser.class)
                .like(dto.getKeywords() != null, AdminUser::getUsername, dto.getKeywords())
                .page(new Page<>(dto.getPage(), dto.getPageSize()));
        // 批量修改密码
        page.getRecords().forEach(item -> item.setPassword("******"));
        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 新增或编辑管理员用户
     * @param user
     */
    @Override
    public void updateAdminUser(AdminUser user) {
        // 用id 判断是否为新增或编辑
        if (user.getId() == null) {
            user.setPassword(DigestUtil.md5Hex(user.getPassword()));
            user.setCreateTime(System.currentTimeMillis());
            user.setUpdateTime(System.currentTimeMillis());
        } else {
            user.setUpdateTime(System.currentTimeMillis());
            // 判断编辑时密码是否被改变
            if (user.getPassword().equals("******")) {
                user.setPassword(null);
            }
        }
        this.saveOrUpdate(user);

    }
}
